<?php
namespace App\Admin\Controllers\Basics;

use App\Admin\Ajax\Basics\AmazonAccountAjax;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductAmazonSku;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Admin as RAdmin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
class AmazonAccountController extends AdminController{

    protected $title = '亚马逊店铺账号';

    protected function grid()
    {
        RAdmin::script($this->_script());
        $grid = new Grid(new AmazonAccount());
        $grid->model()->orderBy('id','DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->country = SysCountry::query()
                    ->whereIn('id',$item->account_country->pluck('country_id'))
                    ->pluck('country');
            }
            return $collection;
        });
        $grid->column('id','ID')->style('width: 5%')->sortable();
        $grid->column('account','账号')->help('可模糊查询');
        $grid->column('is_local','本土账号')->using(AmazonAccount::$_isLocal)->label([1 => 'info', 0 => 'default']);
        $grid->column('aws_region','区域')->display(function ($value){
            return AmazonAccount::$_awsRegion[$value];
        })->filter(AmazonAccount::$_awsRegion);
        $grid->column('country','国家')->label();
        $grid->column('auth_status','授权')->using(AmazonAccount::$_authStatus)->filter(AmazonAccount::$_authStatus)->label([1 => 'success', 0 => 'default']);
        if(Admin::user()->can('account.edit')){
            $grid->column('merchant','卖家编号')->help('可模糊查询');
            $grid->column('auth_at','授权时间')->display(function ($v){
                if($this->api == 1){
                    if($v){
                        $i = strtotime($v) - strtotime('-1 year');
                        if($i <= 0){
                            $str = "<span class='label-danger'>".$v."(已到期)</span>";
                        }elseif($i < AmazonAccount::AUTH_AT_EXPIRED){
                            $str = "<span class='label-warning'>".$v."(即将到期)</span>";
                        }else{
                            $str = "<span class='label-default'>".$v."(已授权)</span>";;
                        }
                        return $str;
                    }else{
                        return '异常';
                    }
                }else{
                    return '';
                }
            });
            $grid->column('api','API')->bool()->filter(AmazonAccount::$_api);
        }
        $grid->column('status','状态')->using(AmazonAccount::$_status)->filter(AmazonAccount::$_status)->label([1 => 'info', 0 => 'danger']);
        if(Admin::user()->can('account.edit')){
            $grid->column('操作')->view('basics.amazon-account.action');
        }else{
            $grid->disableCreateButton();
        }
        $grid->disableActions();
        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->quickSearch('account','merchant');
        $grid->disableFilter();

        return $grid;
    }

    protected function _script()
    {
        $token = csrf_token();

        return <<<EOT
//授权
$('.grid-check-oauth').unbind('click').click(function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    $.ajax({
        method: 'post',
        url: '/xqc/basics/amazon-account-ajax',
        data: {
            _token: "{$token}",
            param:id,
            action:'doOauth'
        },
        success: function (data) {
            if (typeof data === 'object') {
                if (data.status) {
                    swal({
                        title: "跳转亚马逊后台授权？",
                        text: "点击前往将跳转亚马逊店铺后台进行店铺授权，请确保在常用环境操作，避免关联",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "前往",
                        cancelButtonText: "取消",
                        reverseButtons: true,
                    }).then(function(result) {
                        console.log(result)
                        if (result.value) {
                            window.open(data.oauth_url);
                        }
                    });
                } else {
                    swal(data.message, '', 'error');
                }
            }
        }
    });
});
EOT;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new AmazonAccountAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function form()
    {
        $form = new Form(new AmazonAccount());

        $form->hidden('id');

        $form->text('account', '账号')
            ->creationRules(['required', "unique:b_amazon_account"],['required' => '账号必填','unique' => '账号已存在'])
            ->updateRules(['required', "unique:b_amazon_account,account,{{id}}"],['required' => '账号必填','unique' => '账号已存在']);

        //select联动----------
        $form->select('aws_region', '区域')
            ->options(AmazonAccount::$_awsRegion)
            ->required()
            ->load('account_country','/xqc/api-sys/basics-country');

        $form->multipleSelect('account_country', '国家')
            ->options(function (){
                $awsRegion = $this->aws_region ?: old('aws_region');
                $ac = AmazonCountry::options(['aws_region' => $awsRegion]);
                if($ac->isNotEmpty()) {
                    return $ac->toArray();
                }else{
                    return [];
                }
            })
            ->rules("required");

        $form->radio('is_local','是否本土')->options(AmazonAccount::$_isLocal)->default(0);
        //--------------
        $form->radio('api','API')->options(AmazonAccount::$_api)->default(0);
        $form->radio('status','状态')->options(AmazonAccount::$_status)->default(1);
        //API字段------
        $form->display('merchant', '卖家编号')->help('亚马逊API字段-授权后生成');
        $form->display('refresh_token','Token')->help('亚马逊API字段-授权后生成');
        $form->display('auth_at', '授权时间')->help('授权后更新');
        $form->hidden('auth_status', '授权状态')->default(0);
        //--------
        $form->hidden('created_at');
        $form->hidden('updated_at');
        $form->saving(function (Form $form) {
            if ($form->account && $form->model()->account != $form->account) {
                $form->account = strtoupper($form->account);
            }
        });
        $form->saved(function (Form $form) {
            if($form->model()->status == 0){
                ProductAmazonSku::query()
                    ->where('account_id',$form->model()->id)
                    ->where('status',1)
                    ->update(['status' => 2]);
            }
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableView();
            $tools->disableDelete();
        });
        return $form;
    }
}
